package com.yzh.springboot_rbac.service.impl;

import com.yzh.springboot_rbac.entity.Dept;
import com.yzh.springboot_rbac.mapper.DeptMapper;
import com.yzh.springboot_rbac.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptDao;

    /*1.查询所有部门，并进行树结构的方法
    处理从数据库中查找的所有数据，这个数据是一个list集合，创建了所有的节点，在这个方法里面构建树结构*/
    @Override
    public Dept selectAllDept() throws IllegalAccessException {
        /*构建树结构
         *   1.将所有节点放到map集合里面
         *   2.初始化根节点为空
         * */
        List<Dept> deptNodes = deptDao.selectAllDept();
        HashMap<Integer, Dept> hashMap = new HashMap<>();
        Dept root = null;
        for (Dept node : deptNodes) {
            hashMap.put(node.getDeptId(), node);
        }

        /*再次遍历list集合，将其放到父节点里面*/
        for (Dept node : deptNodes) {
            if (node.getParentId() == 0) {
                if (root != null) {
                    throw  new IllegalAccessException("树结构中包含多个根节点");
                }
                root = node;
            } else {
                Dept parentNode = hashMap.get(node.getParentId());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<Dept>());
                    }
                    parentNode.getChildren().add(node);//这个地方一定要在children判断外面执行
                }
            }
        }
        return root;
    }

    @Override
    public boolean isDept(Dept dept) {
        Dept dept1 = deptDao.selectOneDept(dept);
        if (dept1 != null) {
            return false;
        } else {
            int row = deptDao.insertDept(dept);
            if (row > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public boolean isDeletDept(Dept dept) {
        int row = deptDao.deleteDept(dept);
        if (row > 0) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Dept> selectDept(String deptName, String status) {
        List<Dept> depts = deptDao.selectDept(deptName, status);
        return depts;
    }

    @Override
    public Boolean isUpdateDept(Dept dept) {
        Boolean dept1 = deptDao.updateDept(dept);
        if (dept1) {
            return true;
        } else {
            return false;
        }
    }


}
